import { createStore } from 'vuex';
import axios from 'axios';

export default createStore({
  state() {
    return {
      // 用户表格数据
      UserTable: {
        data: [],
        hostsOptions: [], // 确保这里命名正确
        loading: false
      },
      // 参数面板
      PanelParams: {
        begintime: null,
        endtime: null,
        event: null,
        hosts: []
      },
      Past7DaysData: {
        line: [],
        page: [],
        date: []
      },
      Past24hoursData: {
        line: [],
        page: [],
        hour: []
      },

      // 近24小时top_hosts
      Past24HoursTop: {
        line: {
          hosts: [],
          data: []
        },
        page: {
          hosts: [],
          data: []
        }
      },

      // 短链数据
      AllShorts:{
        data:[],
        isloading:false
      },

      // 短链组件
      GroupsShort:{
        data:[],
        isloading:false
      },

      // 短链组数据
      GroupShortLink:[]
    };
  },
  actions: {
    // 用户表格
    getUserTable(context) {
      context.commit('SET_USER_TABLE_LOADING', true); // 修正了命名
      axios.get("https://api.cxkqun.com/index.php/api/query/all", {
        params: {
          'auth': 'cxkqun',
          'limit': 5000,
          'beginTime': formatDate(context.state.PanelParams.begintime),
          'endTime': formatDate(context.state.PanelParams.endtime),
          'event': context.state.PanelParams.event?.code ?? null,
          'hosts': context.state.PanelParams.hosts.join(',')
        }
      }).then(res => {
        if (res.data.code) { // 确保这里的条件检查是你想要的
          const hosts = [...new Set(res.data.data.map(item => item.host))];
          hosts.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
          const obj = {
            data: res.data.data,
            hostsOptions: hosts // 确保这里命名正确
          };
          context.commit('SET_USER_TABLE', obj); // 修正了命名
        }
      }).catch(error => {
        console.error('Error fetching user table:', error);
      }).finally(() => {
        context.commit('SET_USER_TABLE_LOADING', false); // 修正了命名
      });
    },

    // 近7天数据
    getPast7DaysData(context) {
      axios.get("https://api.cxkqun.com/index.php/api/datas/daily", {
        params: {
          'auth': 'cxkqun'
        }
      }).then(res => {
        if (res.data.code) {
          context.commit('GET_PAST_7DAYS_DATA', res.data.data.reverse())
        }
      })
    },

    // 近24小时
    getPast24HoursData(context) {
      axios.get("https://api.cxkqun.com/index.php/api/datas/hourly", {
        params: {
          'auth': 'cxkqun'
        }
      }).then(res => {
        if (res.data.code) {
          context.commit('GET_PAST_24HOURS_DATA', res.data.data.reverse())
        }
      })
    },

    // 近24小时top
    getPast24HoursTopPage(context) {
      axios.get("https://api.cxkqun.com/index.php/api/datas/top?auth=cxkqun").then(res => {
        if (res.data.code) {
          context.commit("GET_PAST_24HOURS_TOP_PAGE", res.data.data)
        }
      })
    },
    getPast24HoursTopLine(context) {
      axios.get("https://api.cxkqun.com/index.php/api/datas/top?auth=cxkqun&event=1").then(res => {
        if (res.data.code) {
          context.commit("GET_PAST_24HOURS_TOP_LINE", res.data.data)
        }
      })
    },

    // 获取短链数据表
    getAllShorts(context){
      context.commit('SET_SHORT_LOADING',true)
      axios.post("https://api.cxkqun.com/index.php/api/short/long", {
        'auth': 'cxkqun',
        'action': 'read'
      }).then(res => {
        if (res.data.code) {
          // 使用map和reduce处理响应数据
          const processedData = res.data.data.map(item => {
            // 计算每个item下所有long项的click_count之和
            const count = item.long.reduce((total, longItem) => total + longItem.click_count, 0);
            // 返回新的item对象，包括计算后的count属性
            return { ...item, count };
          });
  
          // 使用处理后的数据调用mutation
          context.commit('GET_ALL_SHORTS', processedData);
        }
        context.commit('SET_SHORT_LOADING',false)
      })
    },

    // 短链组件
    getGroupShort(context){
      context.commit('SET_GROUP_SHORT_ISLOADING',true)
      axios.get("https://api.cxkqun.com/index.php/api/groups/groups?auth=cxkqun&action=read").then(res => {
        if(res.data.code){
          context.commit('GET_GROUP_SHORT', res.data.data)
        }
        context.commit('SET_GROUP_SHORT_ISLOADING',false)
    })
    },

    // 短链组
    getGroupShortLink(context){
      axios.get("https://api.cxkqun.com/index.php/api/groups/groups?auth=cxkqun&action=read").then(res => {
        if (res.data.code) {
          const tempdata = res.data.data
          context.commit('GET_GROUP_SHORT_LINK', tempdata)
        }
      })
    }
  },
  mutations: {
    SET_USER_TABLE(state, value) {
      state.UserTable.data = value.data;
      state.UserTable.hostsOptions = value.hostsOptions; // 修正了属性名
    },
    SET_USER_TABLE_LOADING(state, value) {
      state.UserTable.loading = value;
    },

    // 近7天数据
    GET_PAST_7DAYS_DATA(state, value) {
      state.Past7DaysData.line = value.map(item => item.event_1_count);
      state.Past7DaysData.page = value.map(item => item.event_not_1_count);
      state.Past7DaysData.date = value.map(item => {
        const [year, month, day] = item.date.split('-');
        return `${month}-${day}`; // 返回月份和日，格式为 MM-DD
      });
    },
    // 近24小时
    GET_PAST_24HOURS_DATA(state, value) {
      state.Past24hoursData.line = value.map(item => item.event_1_count);
      state.Past24hoursData.page = value.map(item => item.event_not_1_count);
      state.Past24hoursData.hour = value.map(item => {
        return item.hourly.substring(11, 13);
      });
    },
    // 近24小时host_top
    GET_PAST_24HOURS_TOP_PAGE(state, value) {
      state.Past24HoursTop.page.hosts = value.map(item => item.host)
      state.Past24HoursTop.page.data = value.map(item => ({
        name: item.host,
        value: item.event_count
      }))
    },
    GET_PAST_24HOURS_TOP_LINE(state, value) {
      state.Past24HoursTop.line.hosts = value.map(item => item.host)
      state.Past24HoursTop.line.data = value.map(item => ({
        name: item.host,
        value: item.event_count
      }))
    },

    // 短链数据
    GET_ALL_SHORTS(state,value){
      state.AllShorts.data = value
    },
    SET_SHORT_LOADING(state,value){
      state.AllShorts.isloading = value
    },

    // 短链组件
    GET_GROUP_SHORT(state,value){
      state.GroupsShort.data = value
    },
    SET_GROUP_SHORT_ISLOADING(state,value){
      state.GroupsShort.isloading = value
    },

    // 短链组
    GET_GROUP_SHORT_LINK(state,value){
      state.GroupShortLink = value
    }

  },
});

// 辅助函数，用于格式化时间对象
function formatDate(date) {
  if (!date) {
    return null;
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}